var app = angular.module('breadTrip', []);
// console.log(obj);
// 浮层样式设置
var windowHeight = $(window).height();
$('#popup-comfirm').find('.popup-inner').css('top', (windowHeight - 191) / 2 - 5);
// 解决jinja2和angular的花括号{{}}冲突的方法
app.config(['$interpolateProvider', function($interpolateProvider) {
    $interpolateProvider.startSymbol('{[');
    $interpolateProvider.endSymbol(']}');
}]);
app.controller('orderController', ['$scope', function($scope){
    $scope.sub_products = obj;  // 产品类型
    $scope.ratio = BT.context('ratio');  // 比率 
    $scope.can_use_coupon = BT.context('can_use_coupon'); // 优惠券是否可用
    
    $scope.res = {}; // 动态数据
    $scope.res.showLayer = false;
    $scope.flag = false;
    /** 
    **  cate              ————  套餐数据
    **  subproductId      ————  产品子类id
    **  singlePrice       ————  产品类型单价price
    **  priceLabelType    ————  产品类型单价id
    **  priceLabel        ————  产品类型单价name
    **  totalPrice        ————  订单总价格
    **  avaliableUserPoints  ————  用户可用积分
    **  usePoints         ————  使用的积分
    **  couponCode        ————  优惠码
    **  couponDiscount    ————  减免折扣
    **  amount            ————  购买数量
    **  agreement         ————  接受协议
    **  data              ————  表单存储数据
    **/ 

    // form 表单数据写入 localStorage
    $scope.setLocalStorage = function(callback){
        var storageObj = $('#form').serializeObject();
        delete storageObj['csrfmiddlewaretoken'];
        localStorage[BT.context('storageName')] = JSON.stringify(storageObj);
        callback && callback();
    };
    // 从 localStorage 中取出 form 表单数据
    $scope.getLocalStorage = function(callback){
        var storageObj = JSON.parse(localStorage.getItem(BT.context('storageName' ))) || {};
        BT.context('storageObj', storageObj);
        callback && callback();
    };
    // 获取产品总价and用户最终支付价格
    $scope.getTotalPrice = function(price){
        $scope.res.totalPrice = price * $scope.res.amount;
        if($scope.res.amount > 0 && $scope.res.cate.extra_price && $scope.res.amount % 2 != 0) $scope.res.totalPrice += $scope.res.cate.extra_price;
        if($scope.can_use_coupon){
            $scope.res.couponDiscount = parseFloat($scope.res.couponDiscount);
            $scope.res.totalPrice -= $scope.res.couponDiscount;
        }
        if($scope.res.avaliableUserPoints != 0){
            if($scope.res.totalPrice < 0){
                $scope.res.totalPrice = 0;
                $scope.res.avaliableUserPoints = 0;
                $scope.res.usePoints = 0;
            }
            $scope.res.usePrice = $scope.res.usePoints * $scope.ratio;
            $scope.res.totalPrice -= $scope.res.usePrice;
        }
        if($scope.res.totalPrice < 0){
            $scope.res.usePoints -= -$scope.res.totalPrice/$scope.ratio;
            if($scope.res.usePoints < 0) $scope.res.usePoints = 0;
            $scope.res.avaliableUserPoints = 0;
            $scope.res.usePrice = 0; 
            $scope.res.totalPrice = 0;
        }
        var n = 0;
        if($scope.res.totalPrice.toString().split('.')[1]) n = 2;
        $scope.res.totalPrice = $scope.res.totalPrice.toFixed(n);
        $('#total_price').val($scope.res.totalPrice)
    };
    // 获取用户可用积分
    $scope.getAvaliablePoints = function(){
        var userPoints = BT.context('userPoints'),
            maxPoints = BT.context('maxPoints'); //用户所有积分
            
        if(maxPoints > 0){
            maxPoints = maxPoints == 9999999 ? 9999999 : (maxPoints * $scope.res.amount);
            extra_price = 0;
            if($scope.res.amount % 2 != 0 && $scope.res.cate.extra_price) extra_price = $scope.res.cate.extra_price;
            // 产品价格换成积分数
            var pricePoints = $scope.res.couponDiscount > 0 ? ($scope.res.singlePrice * $scope.res.amount + extra_price - $scope.res.couponDiscount) : $scope.res.singlePrice * $scope.res.amount + extra_price;
            pricePoints = parseInt(pricePoints/$scope.ratio);
            if(pricePoints < 0) pricePoints = 0;
            maxPoints = (pricePoints > maxPoints) ? maxPoints : pricePoints;
            $scope.res.avaliableUserPoints = maxPoints > userPoints ? userPoints : maxPoints;  
        }else{
            $scope.res.avaliableUserPoints = 0;
        }
        $('#avaliable_user_points').val($scope.res.avaliableUserPoints);
    };
    // 重置折扣信息
    $scope.resetDiscount = function(id){
        $('#price_label_type').val(id);
        $scope.res.couponCode = '';
        $scope.res.couponDiscount = 0;
        $scope.res.usePoints = 0;
        $scope.res.usePrice = 0;
        $('#coupon_code').val('');
        $('#coupon_discount').val(0);
        $('#use_points').val(0);
        $scope.res.singlePrice = parseFloat($scope.getPriceCateData(id).price);
        $('#single_price').val($scope.res.singlePrice);
        $scope.res.priceLabel = $scope.getPriceCateData(id).name;
        $('#price_label').val($scope.res.priceLabel);
        $scope.getAvaliablePoints();
        $scope.getTotalPrice($scope.res.singlePrice);
    };
    // 获取表单存储数据
    $scope.getFormData = function(){
        $scope.getLocalStorage();
        if ( Object.keys(BT.context('storageObj')).length > 0 ) {
            var store_obj = BT.context('storageObj');
            // 选择出行日期后覆盖 localStorage
            if ( BT.context('travelDate') != 'None' ) {
                store_obj.travel_date = BT.context('travelDate');
            }
            $scope.res.data = store_obj;
        }
        // else{
        //     $scope.setLocalStorage();
        // }
    };

    function has_subproduct(id){
        var flag = false;
        for( var i in $scope.sub_products){
            if($scope.sub_products[i].subproduct.id == id){
                flag = true;
            }
        }
        return flag;
    };

    // 方法 ———— 获取产品选中套餐数据
    function getCategory(id){
        for( var i in $scope.sub_products){
            if($scope.sub_products[i].subproduct.id == id){
                return $scope.sub_products[i];
            }
        }
    };

    $scope.getPriceCateData = function(id){
        var price_calendar = $scope.res.cate.price_calendar[0],
            exist = false, 
            array = [];
        for(var k in price_calendar){
            array.push(k);
            if(k == id){
                exist = true;
                return price_calendar[k];
            }
        }
        if(!exist){
            $scope.res.priceLabelType =  array[0];
            return price_calendar[array[0]];
        }
    };

    $scope.init = function(){
        $.extend($.fn, {
            serializeObject: function() {
                var formData = {},
                    formArray = this.serializeArray();
                for(var i = 0, n = formArray.length; i < n; ++i)
                    formData[formArray[i].name] = formArray[i].value;
                return formData;
            }
        });
        // tap默认选择状态
        $scope.getFormData();
        var has = true;
        if($scope.res.data && !has_subproduct( $scope.res.data.sub_product_id)){
            localStorage.removeItem(BT.context('storageName'));
            has = false;
        }
        // 默认选择主价格
        var default_label = '';
        obj[0].price_labels.filter(function(i, k){
            if(i.is_main) default_label = i.id  
        });

        $scope.selected = (has && $scope.res.data && $scope.res.data.sub_product_id && $scope.res.data.sub_product_id != '') ?  parseInt($scope.res.data.sub_product_id) : obj[0].subproduct.id;
        $scope.res.subproductId = $scope.selected; // 产品子类id
        $scope.res.cate = getCategory($scope.selected); 
        $scope.res.cate.extra_price = parseFloat($scope.res.cate.extra_price);
        $scope.res.priceLabelType =  (has && $scope.res.data && $scope.res.data.price_label_type && $scope.res.data.price_label_type != '') ?  parseInt($scope.res.data.price_label_type) : parseInt(default_label);
        $scope.res.amount = (has && $scope.res.data && $scope.res.data.travel_people) ? $scope.res.data.travel_people : 1;
        $scope.res.agreement = ($scope.res.data && has) ? $scope.res.data.agreement ? true : false : true;
        $scope.res.singlePrice = parseFloat($scope.getPriceCateData($scope.res.priceLabelType).price);
        $scope.res.priceLabel = $scope.getPriceCateData($scope.res.priceLabelType).name;
        $scope.res.usePoints = ($scope.res.data && has)  ? $scope.res.data.use_points : 0;
        $scope.res.usePrice = $scope.res.usePoints * $scope.ratio;
        $scope.res.couponCode = ($scope.res.data && has) ? $scope.res.data.coupon_code : '';
        $scope.res.couponDiscount = ($scope.res.data && has) ? $scope.res.data.coupon_discount : 0;
        $scope.getTotalPrice($scope.res.singlePrice);
        $scope.getAvaliablePoints(); 

        $scope.realName = $scope.res.data ? $scope.res.data.real_name : '';
        $scope.mobilePhone = $scope.res.data ? $scope.res.data.mobile_phone : '';
        $scope.emailTxt = $scope.res.data ? $scope.res.data.email : '';
        $scope.addressTxt = $scope.res.data ? $scope.res.data.address : '';
    };

    function scroll(scrollTo, time) {
        var scrollFrom = parseInt(document.body.scrollTop),
            i = 0,
            runEvery = 5; // run every 5ms

        scrollTo = parseInt(scrollTo);
        time /= runEvery;

        var interval = setInterval(function () {
            i++;

            document.body.scrollTop = (scrollTo - scrollFrom) / time * i + scrollFrom;

            if (i >= time) {
                clearInterval(interval);
            }
        }, runEvery);
    };

    $scope.submitForm = function(isValid){
        $scope.setLocalStorage();
        if(!BT.context('UserIsAuthenticated')) {
            btAppSchema.jumpToLogin(location.origin + '/tp/order/?product_id=' + BT.context('productPK'));
            return false;
        } else{
            $scope.res.valid = true;
            if(isValid){
                if($scope.res.usePoints != '0' && $scope.flag == false){
                    $scope.res.showLayer = true;
                    $scope.flag = true;
                    scroll('200px', 10);
                    
                    window.setTimeout(function() {
                        $('body').on('touchmove', function(e){
                            e.preventDefault();
                        });
                    }, 20);
                    return false;
                }
                HTMLFormElement.prototype.submit.call($('#form')[0]);
            }else{
                return false;
            }
        }
    };

    $scope.onKeyDown = function(e){
        if(e.which == 13){
            e.preventDefault();
            return false;
        }
    };

    $scope.focus = function($event){
        var ua = navigator.userAgent.toLocaleLowerCase();
        if(ua.match(/iphone/) && ua.match(/mobile/)){
            $('.total-submit').addClass('bottom');
        } 
    };
    $scope.blur = function(e){
        var ua = navigator.userAgent.toLocaleLowerCase();
        if(ua.match(/iphone/) && ua.match(/mobile/)){
            $('.total-submit').removeClass('bottom');
        }
    };

    $scope.confirmEvent = function(){
        $scope.res.showLayer = false;
        $scope.flag = true;
        $('body').off('touchmove');
        $('#form').trigger('submit');
    };

    $scope.cancelEvent = function(){
        $scope.res.showLayer = false;
        $scope.flag = false;
        $('body').off('touchmove');
    };
  
    // tap点击事件 切换套餐类型
    $scope.tapCtrl = function(id){
        $scope.selected = id;
        if($scope.res.subproductId != id){
            $scope.res.subproductId = id;
            $('#sub_product_id').val(id);
            $scope.res.cate = getCategory(id);
            $scope.res.cate.extra_price = parseFloat($scope.res.cate.extra_price);
            $scope.res.priceLabelType = $scope.res.cate.price_labels[0].id;
            $scope.resetDiscount($scope.res.priceLabelType);
        } 
    };

    $scope.isActive = function(id){
        return $scope.selected == id;
    };

    // 优惠活动事件
    $scope.goHref = function(type){
        $scope.setLocalStorage();
        url = location.origin + '/tp/order/promo/'
            + location.search
            + '&type=' + type;
        if( BT.context('UserIsAuthenticated') ) {
            window.location.href = url;
        } else{
            btAppSchema.jumpToLogin(encodeURIComponent(url)); 
        }
    }
    $scope.init();
}]);
app.controller('changeCateCtrl',['$scope', function($scope){

    $scope.main = function(){
        // tap默认选择状态
        $scope.selected = $scope.res.priceLabelType;
        $scope.$watch("res", function(){
            // $scope.setLocalStorage();
            $scope.selected = $scope.res.priceLabelType;
        }, true);
        setTimeout(function(){
            $scope.setLocalStorage();
        }, 10)

         // 重置高度问题 测试
        var body = document.body,
            html = document.documentElement,
            _height = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );
        $('body').height(_height);
        
    };

    // 订单数量input事件
    $scope.changeAmount = function(val){
        if(val){
            $scope.res.amount = parseInt(Math.abs(val));
        }else{
            $scope.res.amount = 0;
        } 
        $scope.resetDiscount($scope.res.priceLabelType);
        $("#travel_people").val($scope.res.amount);
    };
    
  // tap点击事件 选择子类型
    $scope.tapCtrl = function(id){
        $scope.selected = id;
        if($scope.res.priceLabelType != id){
            $scope.res.priceLabelType = id;
            $scope.resetDiscount(id);
        } 
    };

    $scope.isActive = function(id){
        return $scope.selected == id;
    };

    $scope.main();
}]);
app.directive('stringToNumber', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            ngModel.$parsers.push(function(value) {
                return '' + value;
            });
            ngModel.$formatters.push(function(value) {
                return parseFloat(value, 10);
            });
        }
    };
});
